<template>
  <s-layout>
    <view class="container">
      <view class="form-container">
        <!-- 头部标题 -->
        <view class="header-box" v-if="!formData.id">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">新增消防应急演练</text>
        </view>

        <view class="header-box" v-if="formData.id">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">修改消防应急演练</text>
        </view>

        <!-- 基本信息区块 -->
        <view class="form-card">
          <fui-section
            title="基本信息"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="--fui-section-title-color: #1a1a1a; margin-bottom: 30rpx"
          >
          </fui-section>

          <!-- 演练标题 -->
          <fui-input
            label="演练标题"
            placeholder="请输入演练名称"
            v-model="formData.title"
          >
            <text
              class="cicon-title"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 演练时间 -->
          <view class="form-item" @click="showDatePicker = true">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">演练日期:</text>
            <fui-input
              placeholder="请选择日期"
              v-model="formData.date"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
			  disabled
            >
            </fui-input>
            <fui-date-picker
              :show="showDatePicker"
              type="3"
              @change="confirmDate"
              @cancel="showDatePicker = false"
              style="--fui-datetime-color: #1a1a1a"
            />
          </view>

          <!-- 演练时间 -->
          <view class="form-item">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">持续时长:</text>
            <fui-input
              placeholder="请输入持续时长"
              v-model="formData.duration"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
            >
            </fui-input>
          </view>

          <!-- 演练地点 SAIL输入框-->
          <view class="form-item">
            <text
              class="cicon-location-on"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">演练地点:</text>
            <fui-input
              placeholder="请输入检查人员"
              v-model="formData.address"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
            >
            </fui-input>
          </view>


          <!-- 参与人数 -->
          <view class="form-item">
            <text
              class="cicon-person"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">参与人数：</text>
            <fui-input-number
              v-model="formData.participants"
              custom
              backgroundColor="#FFF"
              :size="30"
              :width="60"
              margin="0"
            >
              <fui-icon name="minussign" :size="48" color="#0052d9"></fui-icon>
              <template v-slot:plus>
                <fui-icon
                  name="plussign-fill"
                  :size="48"
                  color="#0052d9"
                ></fui-icon>
              </template>
            </fui-input-number>
          </view>
        </view>

        <!-- 演练详情区块 -->
        <view class="form-card">
          <fui-section
            title="演练详情"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="--fui-section-title-color: #1a1a1a; margin-bottom: 30rpx"
          >
          </fui-section>

          <!-- 演练流程 -->
          <text class="form-item-title">演练内容：</text>
          <view class="form-item">
            <text
              class="cicon-process"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <fui-textarea
              placeholder="请输入演练内容（每步骤用换行分隔）"
              v-model="formData.content"
              height="200"
              isCounter
              style="flex: 1; --fui-textarea-color: #1a1a1a"
            >
            </fui-textarea>
          </view>

          <!-- 演练总结 -->
          <text class="form-item-title">演练总结：</text>
          <view class="form-item">
            <text
              class="cicon-target"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <fui-textarea
              v-model="formData.purpose"
              isCounter
              height="80rpx"
              placeholder="请输入演练总结"
            ></fui-textarea>
          </view>
        </view>
      </view>

      <!-- 多媒体区块 -->
      <view class="form-card">
        <fui-section
          title="应急演练多媒体"
          line-width="3px"
          line-color="#0052d9"
          isLine
          size="34"
          style="
            padding: 0;
            --fui-section-title-color: #1a1a1a;
            margin-bottom: 30rpx;
          "
        >
        </fui-section>

        <!-- 附件上传组件 -->
        <s-upload
          v-model="formData.file"
          :required="true"
          :initial-images="formData.images"
          :initial-videos="formData.videos"
          :initial-files="formData.files"
          :max-image-count="maxImageCount"
          :max-file-count="maxFileCount"
          :max-video-count="maxVideoCount"
          :max-total-files="maxTotalFiles"
          :upload-url="uploadUrl"
        ></s-upload>

        <!-- 提交按钮 -->
        <view class="submit-btn" @click="handleSubmit">
          <text class="btn-text">提交演练计划</text>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import sUpload from "@/sheep/components/s-upload/s-upload.vue";
const formData = ref({
  id: null,
  title: "",
  date: "",
  address: "",
  participants: "",
  type: "",
  duration: "",
  content: "",
  purpose: "",
  files: [],
  depts: [], // 添加部门字段，避免TypeScript错误
});

// 选择器相关
const showDatePicker = ref(false);


const confirmDate = (e: any) => {
  formData.value.date = e.result;
  showDatePicker.value = false;
  console.log("data", e);
};

// ================ 常量配置 ================
// 上传URL地址
const uploadUrl = "/app_api.php?t=upload&op=image_upload&role=company&type=drill";

// 上传文件数量限制
const maxImageCount = ref(3); // 最大图片数量
const maxFileCount = ref(3); // 最大文件数量
const maxVideoCount = ref(3); // 最大视频数量
const maxTotalFiles = ref(9); // 最大附件总数量


onLoad((options) => {
  if (options.id) {
    const params = {
      dr_id: options.id,
      company_id: sheep.$store("user").userInfo.company_id,
    };
    formData.value.id = options.id;
    sheep.$api.qy_emergency.detail(params).then((res) => {
      console.log("params", params);
      console.log("detail", res);
      
      // 获取详情数据
      const detailData = res.data;
      
      // 转换现有的图片和视频数据为s-upload格式
      const files = [];
      
      // 处理图片数据
      if (detailData.images && detailData.images.length > 0) {
        detailData.images.forEach((img, index) => {
          files.push({
            filePath: img.replace(/^https?:\/\/[^/]+/, ""),
            fileType: "image",
            fileUrl: img,
            id: `file_image_${index}`,
            originalName: `image_${index}`,
            progress: 100,
            uploading: false
          });
        });
      }
      
      // 处理视频数据
      if (detailData.videos && detailData.videos.length > 0) {
        detailData.videos.forEach((video, index) => {
          files.push({
            filePath: video.replace(/^https?:\/\/[^/]+/, ""),
            fileType: "video",
            fileUrl: video,
            id: `file_video_${index}`,
            originalName: `video_${index}`,
            progress: 100,
            uploading: false
          });
        });
      }
      
      // 更新表单数据
      formData.value = {
        ...detailData,
        file: files
      };
    });
  } else {
    // 默认数据，用于测试
    formData.value = {
      id: null,
      title: "",
      date: "",
      address: "",
      participants: "",
      type: "",
      duration: "",
      purpose: "",
      content: "",
      files: [],
    };
  }
});
// 注意：详情数据已在onLoad函数中处理

// 表单提交
const handleSubmit = () => {
  // 验证表单数据
  if (!validateForm()) return;
  
  // 从files数组中提取图片和视频
  // 从files中分离出不同类型的文件
  const images = [];
  const videos = [];
  const files = [];

  // 处理上传的文件
  formData.value.file.forEach(file => {
    if (file.fileType === "image") {
      images.push(file.filePath);
    } else if (file.fileType === "video") {
      videos.push(file.filePath);
    } else if (file.fileType === "file") {
      files.push(file.filePath);
    }
  });
  
  const data = {
    dr_id: formData.value.id,
    dr_content: formData.value.content,
    dr_title: formData.value.title,
    dr_date: formData.value.date,
    dr_address: formData.value.address,
    dr_participants: formData.value.participants,
    dr_type: formData.value.type,
    dr_duration: formData.value.duration,
    dr_images: images,
    dr_videos: videos,
    dr_files:files,
    dr_purpose: formData.value.purpose,
    company_id: sheep.$store("user").userInfo.company_id,
  };
  
  console.log("提交数据", data);
  
  if (formData.value.id) {
    sheep.$api.qy_emergency.updata(data).then((res) => {
      console.log("update", res);
      uni.showLoading({ title: "提交中...", mask: true });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({ title: "提交成功", icon: "success" });
        
        // 先发出刷新事件通知，这样接收页面可以准备好
        uni.$emit('emergencyDataUpdated', {
          timestamp: Date.now(),
          action: 'update',
          moduleType: 'emergency'
        });
        
        // 然后再返回上一页
        uni.navigateBack();
      }, 1000);
    });
  } else {
    sheep.$api.qy_emergency.add(data).then((res) => {
      console.log("add", res);
      uni.showLoading({ title: "提交中...", mask: true });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({ title: "提交成功", icon: "success" });
        
        // 先发出刷新事件通知，这样接收页面可以准备好
        uni.$emit('emergencyDataUpdated', {
          timestamp: Date.now(),
          action: 'add',
          moduleType: 'emergency'
        });
        
        // 然后再返回上一页
        uni.navigateBack();
      }, 1500);
    });
  }
};

const validateForm = () => {
  if (!formData.value.title) {
    uni.showToast({ title: "请填写演练标题", icon: "none" });
    return false;
  }
  if (!formData.value.date) {
    uni.showToast({ title: "请选择演练时间", icon: "none" });
    return false;
  }
  if (!formData.value.duration) {
    uni.showToast({ title: "请填写持续时长", icon: "none" });
    return false;
  }
  if (!formData.value.address) {
    uni.showToast({ title: "请填写演练地点", icon: "none" });
    return false;
  }
  if (!formData.value.participants || formData.value.participants <= 0) {
    uni.showToast({ title: "请填写正确的参与人数", icon: "none" });
    return false;
  }
  if (!formData.value.content) {
    uni.showToast({ title: "请填写演练内容", icon: "none" });
    return false;
  }
  if (!formData.value.purpose) {
    uni.showToast({ title: "请填写演练总结", icon: "none" });
    return false;
  }
  if (!formData.value.file || formData.value.file.length === 0) {
    uni.showToast({ title: "请至少上传一个附件", icon: "none" });
    return false;
  }
  return true;
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background: #f8f9fa;
  min-height: 100vh;
}

.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
}

.form-item-title {
  display: flex;
  align-items: center;
  padding-top: 20rpx;
  padding-left: 32rpx;
  font-size: 32rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  font-size: 32rpx;
  border-bottom: 1rpx solid #eee;
}

.upload-item {
  margin-top: 30rpx;
  .upload-box {
    height: 200rpx;
    background: #ecf5ff;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
  }
}

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
  .btn-text {
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
  }
}
</style>
